package com.ogilvy.audi.webapp.action.page;


import com.ogilvy.audi.model.util.PageParameter;
import com.ogilvy.audi.service.GenericManager;
import com.ogilvy.audi.util.PageConstants;
import com.ogilvy.audi.webapp.action.BaseAction;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.json.annotations.JSON;
import org.displaytag.tags.TableTagParameters;
import org.displaytag.util.ParamEncoder;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: User
 * Date: 2009-1-12
 * Time: 0:51:54
 * To change this template use File | Settings | File Templates.
 */
public abstract class PageAction extends BaseAction {
    	protected static int PAGE_SIZE = PageConstants.DEFAULT_DISPLAYTAG_SIZE;
        protected String name;
        protected String description;
        protected String startDate;
        protected String endDate;
        protected String ids;
        protected String fromUrl;
     @JSON(serialize=false)
	protected String getSortColumn(HttpServletRequest aRequest, String aTableId) {
		return aRequest.getParameter(new ParamEncoder(aTableId)
				.encodeParameterName(TableTagParameters.PARAMETER_SORT));
	}
     @JSON(serialize=false)
	protected String getSortOrder(HttpServletRequest aRequest, String aTableId) {
		return aRequest.getParameter(new ParamEncoder(aTableId)
				.encodeParameterName(TableTagParameters.PARAMETER_ORDER));
	}


  @JSON(serialize=false)
	protected int getPageNumber(HttpServletRequest aRequest, String aTableId) {
		String pageNumberString = aRequest.getParameter(new ParamEncoder(
				aTableId)
				.encodeParameterName(TableTagParameters.PARAMETER_PAGE));
    // String   pageNumberString=  aRequest.getParameter("pageNum");
      // log.debug("The pagerNum is "+pageNumberString) ;
		int pageNumber = 1;
		if (!StringUtils.isBlank(pageNumberString)) {
			try {
				pageNumber = (Integer.parseInt(pageNumberString));
			} catch (NumberFormatException e) {
				// Do nothing... assume startRecord is 0;
			}
		}
		return pageNumber;
	}


    @JSON(serialize=false)
	protected String getExporting(HttpServletRequest aRequest, String aTableId) {
		return aRequest.getParameter(new ParamEncoder(aTableId)
				.encodeParameterName(TableTagParameters.PARAMETER_EXPORTING));
	}
    @JSON(serialize=false)
	protected String getExportType(HttpServletRequest aRequest, String aTableId) {
		return aRequest.getParameter(new ParamEncoder(aTableId)
				.encodeParameterName(TableTagParameters.PARAMETER_EXPORTTYPE));
	}

	public List searchCondition(String equals,String... paras){
      // PageConstants.initConditionMap();
          if(null==equals)
            equals="";
         HttpServletRequest request=this.getRequest();
		String TABLE_ID = getTableId();
		int page_size = getPageSize();
		GenericManager mgr = getManager();
		String sortColumn = getSortColumn(request, TABLE_ID);
		String sortOrder = getSortOrder(request, TABLE_ID);
		int pageNumber = getPageNumber(request, TABLE_ID);
		int firstRecord = (pageNumber - 1) * page_size;
		String exporting = getExporting(request, TABLE_ID);
		String exportType = getExportType(request, TABLE_ID);
		String resultSql = "first";
        String order="desc";
		// Just get the items on the current page.
		if (request.getAttribute(getTableId()) == null) {
           Map condition=getSearchCondition();
              log.debug("The search conditon size is **"+condition.size());
             if(StringUtils.isNotBlank(sortOrder)){
                 if(sortOrder.equals("1"))
                    order="asc";
             }
             if(StringUtils.isNotBlank(sortColumn)){
               List sortList=(List)condition.get(PageConstants.DEFAULT_SORT_NAME);
                 PageParameter sortPar=new PageParameter();
                  sortPar.setParName(sortColumn);
                  sortPar.setParValue(order);
                sortList.add(sortPar);
             }
            List list= mgr.getRecordsByCondition(
					firstRecord, page_size,  condition,equals);
			request.setAttribute(getTableId(),list);
			resultSql = (String) condition.get("resultsql");


			Collection dateSet = (Collection) condition.get("dateSet");
			request.setAttribute("resultSize", mgr
					.getRecordSizeBySql(resultSql,dateSet));
            request.setAttribute("pageSize",page_size);
            request.setAttribute("currentPage",pageNumber);
			if (log.isDebugEnabled()) {
				log.debug("return sql is " + resultSql);
			}
            return list;
		}
        return new ArrayList();
	}



     @JSON(serialize=false)
	public  int getPageSize(){
         String pageSize= this.getRequest().getParameter("pageSize");
         log.debug("The pageSize is "+pageSize) ;
            if(StringUtils.isBlank(pageSize))
		return PAGE_SIZE;
          else
         return     Integer.valueOf(pageSize);
	}


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getStartDate() {
        return startDate;
    }

    public void setStartDate(String startDate) {
        this.startDate = startDate;
    }

    public String getEndDate() {
        return endDate;
    }

    public void setEndDate(String endDate) {
        this.endDate = endDate;
    }

    public String getIds() {
        return ids;
    }

    public void setIds(String ids) {
        this.ids = ids;
    }

    public String getFromUrl() {
        return fromUrl;
    }

    public void setFromUrl(String fromUrl) {
        this.fromUrl = fromUrl;
    }

    public  Map getSearchCondition(){
        log.debug("Entering super getSearchCondition method");
      Map condition =PageConstants.initConditionMap();
      List parList=(List)condition.get(PageConstants.DEFAULT_PARA_NAME);
      List dateList=(List)condition.get(PageConstants.DEFAULT_DATE_NAME);
      List sortList=(List)condition.get(PageConstants.DEFAULT_SORT_NAME);
        if(StringUtils.isNotBlank(name)){
           PageParameter par=new PageParameter();
            par.setParName("geneAttribute.name");
            par.setParValue(name);
            par.setFuzzyStatus(true);
            parList.add(par);
        }

         if(StringUtils.isNotBlank(description)){
            PageParameter par=new PageParameter();
            par.setParName("geneAttribute.description");
            par.setParValue(description);
            par.setFuzzyStatus(true);
            parList.add(par);
        }
        if(StringUtils.isNotBlank(startDate)){
            PageParameter date=new PageParameter();
            date.setParName("geneAttribute.createTime");
            date.setParValue(startDate);
              date.setCompareSymbol(">=");
            dateList.add(date);
        }

        if(StringUtils.isNotBlank(endDate)){
            PageParameter date=new PageParameter();
            date.setParName("geneAttribute.createTime");
            date.setParValue(endDate);
              date.setCompareSymbol("<=");
            dateList.add(date);
        }



       return PageConstants.condition;
    }


//    public void  initConditionMap(){
//         log.debug("Entering initConditionMap method");
//        Map condition =PageConstants.condition;
//        condition.clear();
//         List<PageParameter> pars=new ArrayList();
//         List<PageParameter> dates=new ArrayList();
//         List<PageParameter> sorts=new ArrayList();
//
//         condition.put(PageConstants.DEFAULT_PARA_NAME,pars);
//         condition.put(PageConstants.DEFAULT_DATE_NAME,dates);
//         condition.put(PageConstants.DEFAULT_SORT_NAME,sorts);
//    }


    public  abstract GenericManager getManager();

	public abstract String getTableId();


}